package com.novel.resource.qiniu.impl;

import com.novel.common.resource.IResourceService;
import com.novel.resource.qiniu.QiniuClient;
import com.qiniu.util.IOUtils;

import java.io.*;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 资源存储服务实现类
 *
 * @author novel
 * @date 2019/6/4
 */
public class QiniuResourceServiceImpl implements IResourceService {
    /**
     * qiniu 客户端
     */
    private QiniuClient qiniuClient;
    /**
     * 文件访问连接最大超时时间
     */
    private int fileCacheMaxTime;


    public QiniuResourceServiceImpl(QiniuClient qiniuClient, int fileCacheMaxTime) {
        this.fileCacheMaxTime = fileCacheMaxTime;
        this.qiniuClient = qiniuClient;
    }

    @Override
    public String getFileUrl(String sourceUrl) throws IOException {
        String encodedFileName = URLEncoder.encode(sourceUrl, "utf-8").replace("+", "%20");
        String publicUrl = String.format("%s/%s", this.qiniuClient.getQiniuConfig().getDomainOfBucket(), encodedFileName);
        return this.qiniuClient.getAuth().privateDownloadUrl(publicUrl, 1000L * 60 * fileCacheMaxTime);
    }

    @Override
    public boolean upLoadFile(String sourceUrl, String destPath) throws IOException {
        qiniuClient.getUploadManager().put(sourceUrl, destPath, qiniuClient.getUploadToken());
        return true;
    }

    @Override
    public boolean upLoadFile(InputStream source, String destPath) throws IOException {
        qiniuClient.getUploadManager().put(source, destPath, qiniuClient.getUploadToken(), null, null);
        return true;
    }

    @Override
    public void download(String filePath, String localPath) throws IOException {
        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        URL url = new URL(this.getFileUrl(filePath));
        //下载存放的位置
        File outFile = new File(localPath);
        OutputStream os = new FileOutputStream(outFile);

        InputStream is = url.openStream();
        byte[] buff = new byte[1024];
        while (true) {
            int read = is.read(buff);
            if (read == -1) {
                break;
            }
            byte[] temp = new byte[read];
            System.arraycopy(buff, 0, temp, 0, read);
            os.write(temp);
        }
        is.close();
        os.close();
    }


    @Override
    public boolean delete(String filePath) throws IOException {
        // 删除文件。
        qiniuClient.getBucketManager().delete(qiniuClient.getQiniuConfig().getBucketName(), filePath);
        return true;
    }

    @Override
    public byte[] readBytes(String filePath) throws IOException {
        URL url = new URL(this.getFileUrl(filePath));
        InputStream is = url.openStream();
        return IOUtils.toByteArray(is);
    }
}
